import base64
from io import BytesIO
from datetime import datetime
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.custom_captcha import create_captcha_image, generate_captcha_text
from .authentications import generate_jwt
from .serializers import LoginSerializer, UserSerializer, RestPwdSerializer
from captcha.models import CaptchaStore


# Create your views here.
class LoginView(APIView):
    def post(self, request):
        # 验证数据
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            user.last_login = datetime.now()
            user.save()
            token = generate_jwt(user)
            return Response({'token': token, 'user': UserSerializer(user).data}, status=status.HTTP_200_OK)
        else:
            # 字典.values()  返回的是一个 dict_value对象
            # print(list(serializer.errors.values())[0][0])
            detail = list(serializer.errors.values())[0][0]
            # 和 drf 返回错误得到参数名保持一致
            return Response({"detail": detail}, status=status.HTTP_400_BAD_REQUEST)


# class AuthenticatedRequireView(APIView):
#     permission_classes = [IsAuthenticated]


class ResetPwdView(APIView):
    def post(self, request):
        # 这个request 是DRF封装的， rest_framework.request.Request
        # 想要获取django的原生request对象需要request._request
        serializer = RestPwdSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            new_password1 = serializer.validated_data['newPwd1']
            request.user.set_password(new_password1)
            request.user.save()
            return Response()
        else:
            print(serializer.errors)
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail": detail}, status=status.HTTP_400_BAD_REQUEST)


class CaptchaView(APIView):
    def get(self, request):
        # 生成一个新的验证码
        image_size = settings.CAPTCHA_IMAGE_SIZE
        font_size = settings.CAPTCHA_FONT_SIZE
        length = settings.CAPTCHA_LENGTH
        # 生成包含大小写的验证码
        captcha_code = generate_captcha_text(length)
        captcha_store = CaptchaStore()
        captcha_store.challenge = captcha_code
        captcha_store.response = captcha_code
        captcha_store.save()
        hashkey = captcha_store.hashkey
        captcha = CaptchaStore.objects.get(hashkey=hashkey)
        print(captcha.challenge, captcha.response, captcha.hashkey)

        captcha_image = create_captcha_image(captcha_code, image_size, font_size)

        # 将验证码图片转换为 Base64
        buffer = BytesIO()
        captcha_image.save(buffer, format='PNG')
        image_base64 = f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode('utf-8')}"

        return Response({'captcha_key': hashkey, 'image_base64': image_base64})

    def post(self, request):
        captcha_key = request.data.get('captcha_key')
        captcha_response = request.data.get('captcha_response')

        # 验证验证码
        try:
            captcha = CaptchaStore.objects.get(hashkey=captcha_key)
            if captcha.response.lower() == captcha_response.lower():
                captcha.delete()  # 验证成功后删除验证码
                return Response(status=status.HTTP_200_OK)
            else:
                captcha.delete()  # 验证失败后删除验证码
                return Response(data={'detail': "验证失败(2)"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(e)
            return Response(data={'detail': "验证失败(1)"}, status=status.HTTP_400_BAD_REQUEST)
